<template>
  <!-- vue-codemirror -->
  <div class="h-10">
    <a-select
      class="w-60"
      ref="select"
      v-model:value="value1"
      @focus="focus"
      @change="handleChange"
    >
      <a-select-option value="jack">Jack</a-select-option>
      <a-select-option value="lucy">Lucy</a-select-option>
      <a-select-option value="disabled" disabled>Disabled</a-select-option>
      <a-select-option value="Yiminghe">yiminghe</a-select-option>
    </a-select>
  </div>
  <div class="flex flex-auto h-96">
    <div class="w-3/6">
      <codemirror
        v-model="code"
        placeholder="请在此处输入代码"
        :style="{ width: '100%', height: '100%' }"
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="2"
        :extensions="extensions"
        @update="codeContentUpdate"
      />
    </div>
    <div class="code-preview w-3/6">
      <p>{{ codeForShow }}</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Codemirror } from 'vue-codemirror'
import { ViewUpdate } from '@codemirror/view'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'

const code = ref('')
const codeForShow = ref<any>('预览界面')
const value1 = ref<string>('')
// 监听编辑器界面的动态调整
const extensions = computed(() => {
  const result = [javascript(), oneDark]
  return result
})

// Codemirror EditorView instance ref
// const view = shallowRef()
// const handleReady = (payload: any) => {
//   view.value = payload.view
// }

const log = (paramsA: any, paramsB: any) => {
  console.log(paramsA, paramsB)
}

const focus = () => {
  // console.log('focus')
}

const state = reactive({
  lines: null as null | number,
  cursor: null as null | number,
  selected: null as null | number,
  length: null as null | number
})
const codeContentUpdate = (viewUpdate: ViewUpdate) => {
  codeForShow.value = code
  // console.log('预览结果', viewUpdate)
  // console.log('预览结果-code', code)
  const ranges = viewUpdate.state.selection.ranges
  state.selected = ranges.reduce((plus, range) => plus + range.to - range.from, 0)
  state.cursor = ranges[0].anchor
  // length
  state.length = viewUpdate.state.doc.length
  state.lines = viewUpdate.state.doc.lines
  log('viewUpdate', viewUpdate)
  console.log('state', state)
}

const handleChange = (value: any) => {
  console.log(`selected ${value}`)
}

// // Status is available at all times via Codemirror EditorView
// const getCodemirrorStates = () => {
//   const state = view.value.state
//   const ranges = state.selection.ranges
//   const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
//   const cursor = ranges[0].anchor
//   const length = state.doc.length
//   const lines = state.doc.lines
//   // more state info ...
//   // return ...
// }
</script>
